/**
 * 泛娱区块链 - BindingPhone
 * http://menger.me
 * @author: zaric
 * @creation time: 2018-12-08
 */


'use strict';
import React from 'react';
import {StyleSheet, View,} from 'react-native';
import NavigationBar from '../../component/navigation/NavigationBar';
import Container from '../../component/common/Container';
import TextInput from '../../component/common/TextInput';
import Button from '../../component/common/Button';
import {inject, observer} from 'mobx-react';
import VerificationCode from '../../component/common/VerificationCode';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import SegmentedView from "../../component/segmented/SegmentedView";

@inject('appStore', 'loginStore')
@observer
class BindingPhone extends React.Component {

    constructor(props) {
        super(props);
        this.inputData = {
            memberPhone: '',
            memberPassword: '',
        };
        this.state = {codeOpen: false};
        this.params = this.props.navigation.state.params;
        this.type = this.params.type;
        this.token = this.params.token;
        this.user_id = this.params.user_id;
        // console.log('this.params--->', this.params);
    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    _onPressBack = () => {
        RouterHelper.goBack()
    };

    _onPressRegister = async (account_type) => {
        let {loginStore} = this.props;
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };
        if (!this.inputData['memberPhone']) {
            params['detail'] = '请检查手机号输入是否正确';
            AlertManager.show(params)
        } else if (!this.inputData['code'] || this.inputData['code'].length < 4) {
            params['detail'] = '请检查验证码是否输入正确';
            AlertManager.show(params)
        } else if (this.inputData['memberPassword'].length === 0) {
            params['detail'] = '请输入密码';
            AlertManager.show(params)
        } else if (this.inputData['memberPassword'] !== this.inputData['memberPasswordTwo']) {
            params['detail'] = '两次输入的密码不一致';
            AlertManager.show(params)
        } else {
            let tokenPar = {};
            if (this.type === 'wx_login') {
                tokenPar.wx_token = this.token;
            } else {
                tokenPar.qq_token = this.token;
            }

            let url = account_type === 'new' ? ServicesApi.USER_REGISTER : ServicesApi.BIND_PLATFORM;
            let params = {
                user_phone: this.inputData['memberPhone'],
                user_password: this.inputData['memberPassword'],
                captcha: this.inputData['code'],
                type: 'phone_register',
                ...tokenPar
            };
            if (account_type === 'new') {
                params = {
                    user_id: this.user_id,
                    ...params,
                };
            }
            let result = await loginStore.postRequest(url, params);
            // console.log('绑定手机返回---------->',result);
            if (result.code === StatusCode.SUCCESS_CODE) {
                ToastManager.show('绑定成功!');
                RouterHelper.goBack();
            } else {
                ToastManager.show(result.dec || 'error')
            }
        }
    };

    _onPressVer = async () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                    }
                }
            ]
        };

        if (!this.inputData['memberPhone']) {
            params['detail'] = '请检查手机号输入是否正确'
            AlertManager.show(params);
            return;
        }

        let {loginStore} = this.props
        let data = {phone: this.inputData['memberPhone'], sms_model: 'register_sms_model'};
        let result = await loginStore.postRequest(ServicesApi.COMMON_SEND_SMS, data);
        if (result.code === 0) {
            ToastManager.show('获取验证码成功!')
            this.setState({codeOpen: true})
        } else {
            ToastManager.show(result.msg)
        }
        // console.log(result)

    }

    _onPressNavigate = (component) => {
        RouterHelper.navigate(component)
    }

    _onChangeText = (key, text) => {
        this.inputData[key] = text
    };

    _onStopInterval = () => {
        this.setState({codeOpen: false})
    };

    //渲染内容视图
    _renderContent = (account_type) => {
        let {codeOpen} = this.state;
        return (
            <KeyboardAwareScrollView>
                <View style={styles.headerContainer}>
                    <View style={styles.loginInputStyle}>
                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text) => this._onChangeText('memberPhone', text)}
                            placeholder={'手机号'}
                            keyboardType={'numeric'}
                        />
                    </View>
                    <View style={[styles.inputLine, {marginLeft: 30}]}/>
                    <View style={styles.loginInputStyle}>
                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text) => this._onChangeText('code', text)}
                            placeholder={'验证码'}
                            keyboardType={'numeric'}
                        />
                        <VerificationCode
                            open={codeOpen}
                            onStopInterval={this._onStopInterval}
                            onPress={this._onPressVer} style={styles.getCodeStyle}>获取验证码</VerificationCode>
                    </View>
                    <View style={styles.pwdStyle}>
                        <View style={styles.inputLine}/>
                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            placeholder={'输入密码'}
                            onChangeText={(text) => this._onChangeText('memberPassword', text)}
                            secureTextEntry={true}
                        />
                        <View style={styles.inputLine}/>
                    </View>
                    <View style={styles.pwdStyle}>
                        <TextInput
                            style={styles.inputStyle}
                            underlineColorAndroid={'transparent'}
                            placeholder={'确认密码'}
                            onChangeText={(text) => this._onChangeText('memberPasswordTwo', text)}
                            secureTextEntry={true}
                        />
                        <View style={styles.inputLine}/>
                    </View>
                    <Button style={styles.button} title={'完成'} onPress={() => this._onPressRegister(account_type)}/>
                </View>
            </KeyboardAwareScrollView>
        )
    };

    render() {
        return (
            <Container style={styles.container} keyboardShouldPersistTaps={true}>
                <NavigationBar
                    title={'北链泛娱'}
                />
                <SegmentedView
                    ref={(v) => this.segmentedRef = v}
                    justifyItem={'fixed'}
                    showSegmentedBar={true}
                    scrollEnabled={true}
                    indicatorLineWidth={3}
                    indicatorLineColor={Theme.themeColor}
                    indicatorPositionPadding={0}
                    style={styles.headerTitle}
                    keyboardShouldPersistTaps={'always'}
                >
                    <View
                        title={'绑定新账号'}
                        style={styles.segmentedItem}
                        titleStyle={styles.titleStyle}
                        activeTitleStyle={styles.activeTitleStyle}
                    >
                        {this._renderContent('new')}
                    </View>
                    <View
                        title={'绑定已有账号'}
                        style={styles.segmentedItem}
                        titleStyle={styles.titleStyle}
                        activeTitleStyle={styles.activeTitleStyle}
                    >
                        {this._renderContent('old')}
                    </View>
                </SegmentedView>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // paddingTop: 94,
        backgroundColor: '#fff',
    },
    headerContainer: {
        flex: 1,
        marginTop: 51
    },
    headerTitle: {
        flex: 1,
        paddingTop: 40,
    },
    segmentedItem: {
        flex: 1,
    },
    titleStyle: {
        color: '#333',
        fontSize: FontSize(16),
    },
    activeTitleStyle: {
        fontSize: FontSize(16),
        color: Theme.themeColor,
    },

    arrow: {
        width: 7,
        height: 8,
    },
    titleHint: {
        textAlign: 'center',
        fontSize: FontSize(12),
        marginTop: 19,
        color: '#3a3a3a'
    },
    content: {
        flex: 1,
    },

    loginInputStyle: {
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 30,
    },
    pwdStyle: {
        height: 60,
        marginLeft: 30,
    },
    hintText: {
        fontSize: FontSize(16),
        color: '#333'
    },
    inputStyle: {
        flex: 1,
        fontSize: FontSize(16),
        height: 44,
        // backgroundColor: 'red',
    },
    inputLine: {
        backgroundColor: '#ececec',
        height: 1,
        marginRight: 30,
        marginTop: 5,
    },


    button: {
        marginTop: 77,
        marginHorizontal: 30,
        backgroundColor: Theme.themeColor,
        color: '#fff'
    },
    getCodeStyle: {
        borderLeftWidth: 1,
        borderColor: '#ffefe0',
        paddingLeft: 16,
        color: '#ffcc9b',
        marginRight: 30,
    }
});

export default BindingPhone